package xyz.xujn.bcp.ldap.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.LdapContextSource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import java.util.Hashtable;
import java.util.List;

@RestController
@RequestMapping("/ldap")
public class LdapController {

	@Autowired
	private LdapTemplate ldapTemplate;


	@GetMapping("/list")
	public Object search() {
		list();
		return ldapTemplate.lookup("uid=bob,ou=people,dc=springframework,dc=org");
//		return ldapTemplate
//				.search(
//						"dc=springframework,dc=org",
//						"cn=slash/guy" ,
//						(AttributesMapper<String>) attrs -> (String) attrs.get("cn").get());

	}

	public void list() {
		LdapContextSource ldapContextSource = new LdapContextSource();
		ldapContextSource.setPassword("123456");
		ldapContextSource.setUrl("ldap://localhost:389");
		ldapContextSource.setBase("dc=springframework,dc=org");
		ldapContextSource.setUserDn("cn=admin,dc=springframework,dc=org");
		ldapContextSource.afterPropertiesSet();

		LdapTemplate ldapTemplate = new LdapTemplate(ldapContextSource);
		ldapTemplate.setIgnorePartialResultException(true);
		ldapTemplate.setDefaultTimeLimit(1000);
		ldapTemplate.setDefaultCountLimit(100);

			List<String> list = ldapTemplate
				.search(
						"",
						"cn=slash/guy",
						(AttributesMapper<String>) attrs -> (String) attrs.get("cn").get());
		System.out.println(list);
	}

	public DirContext getDirContext() {
		Hashtable env = new Hashtable();
		env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
		env.put(Context.PROVIDER_URL, "ldap://localhost:389/cn=admin,dc=springframework,dc=org");
		env.put(Context.SECURITY_PRINCIPAL, "123456");

		DirContext ctx;
		try {
			ctx = new InitialDirContext(env);
		} catch (NamingException e) {
			throw new RuntimeException(e);
		}

		return ctx;
	}
}
